package com.newthread.android.ui.bbs;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.Conversation;
import com.actionbarsherlock.app.SherlockFragment;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.newthread.android.R;
import com.newthread.android.bean.StudentUserLocal;
import com.newthread.android.util.ImageUtil;
import com.newthread.android.util.Loger;
import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.annotation.view.ViewInject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by jindongping on 15/6/4.
 */
public class BbsHistoryFrament extends SherlockFragment {
    private LayoutInflater inflater;
    private List<HistoryData> mDatas;
    private HistoryAdpter adpter;
    private FinalDb db;
    private PullToRefreshListView refreshListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        db = FinalDb.create(getActivity(), "onMinDaBbs");
        inData();
    }


    private void inData() {
        mDatas = getHistoryData(JMessageClient.getConversationList());
        Collections.sort(mDatas, new Comparator<HistoryData>() {
            @Override
            public int compare(HistoryData lhs, HistoryData rhs) {
                return (int) (rhs.getDate() - lhs.getDate());
            }
        });
        adpter = new HistoryAdpter(getActivity(), R.layout.bbs_history_item, mDatas);
    }

    private List<HistoryData> getHistoryData(List<Conversation> conversationList) {
        List<HistoryData> datas = new ArrayList<>();
        for (Conversation conversation : conversationList) {
            try {
                StudentUserLocal user = db.findAllByWhere(StudentUserLocal.class, "studentId=\"" + conversation.getTargetId() + "\"").get(0);
                HistoryData data = null;
                switch (conversation.getLatestType()) {
                    case text:
                        data = new HistoryData(conversation.getLatestText(), user.getHeadPhotoUrl(), user.getName(), user.getStudentId(), conversation.getLastMsgDate());
                        break;
                    case voice:
                        data = new HistoryData("语音", user.getHeadPhotoUrl(), user.getName(), user.getStudentId(), conversation.getLastMsgDate());
                        break;
                }
                datas.add(data);
            }catch (Exception e){
                Loger.V("未先缓存所有用户数据");
            }
        }
        return datas;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        View viewRoot = inflater.inflate(R.layout.fragment_bbs_history, container, false);
        //注意这里不能使用ViewInject 否则 fargemnt切换后 OnCreateView listview不显示
        refreshListView = (PullToRefreshListView) viewRoot.findViewById(R.id.refreshListView);
        inView();
        return viewRoot;
    }

    private void inView() {
        refreshListView.setAdapter(adpter);
        refreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), BbsChatActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("target_id", mDatas.get(position - 1).getStudentId());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(final PullToRefreshBase<ListView> refreshView) {
                inData();
                refreshListView.setAdapter(adpter);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshView.onRefreshComplete();
                    }
                }, 200);
            }
        });
    }

    private class HistoryAdpter extends ArrayAdapter<HistoryData> {

        public HistoryAdpter(Context context, int resource, List<HistoryData> objects) {
            super(context, resource, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.bbs_history_item, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            HistoryData itemData = getItem(position);
            ImageUtil.getInstance(inflater.getContext()).disPalyImage(itemData.getHeadPhotoUrl(), holder.imageView);
            holder.name.setText(itemData.getName());
            holder.lastMessage.setText(itemData.getLastMessage());
            return convertView;
        }
    }

    static class ViewHolder {
        @ViewInject(id = R.id.bbs_history_headPhoto)
        private ImageView imageView;
        @ViewInject(id = R.id.bbs_history_name)
        private TextView name;
        @ViewInject(id = R.id.bbs_history_lastMessage)
        private TextView lastMessage;

        public ViewHolder(View view) {
            FinalActivity.initInjectedView(this, view);
        }
    }

    class HistoryData {

        private String lastMessage;//最后一条消息
        private String headPhotoUrl;//头像地址
        private String name;//姓名
        private String studentId;//学号
        private long date;//最后一条日期

        public HistoryData(String lastMessage, String headPhotoUrl, String name, String studentId, long date) {
            this.lastMessage = lastMessage;
            this.headPhotoUrl = headPhotoUrl;
            this.name = name;
            this.studentId = studentId;
            this.date = date;
        }

        public String getLastMessage() {
            return lastMessage;
        }

        public void setLastMessage(String lastMessage) {
            this.lastMessage = lastMessage;
        }

        public String getHeadPhotoUrl() {
            return headPhotoUrl;
        }

        public void setHeadPhotoUrl(String headPhotoUrl) {
            this.headPhotoUrl = headPhotoUrl;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getStudentId() {
            return studentId;
        }

        public void setStudentId(String studentId) {
            this.studentId = studentId;
        }

        public long getDate() {
            return date;
        }

        public void setDate(long date) {
            this.date = date;
        }
    }

}
